import Taro, { useDidShow, setNavigationBarTitle, redirectTo } from '@tarojs/taro'
import { View, Image, Button, Textm, Navigator, Text } from '@tarojs/components'
import { AtIcon } from 'taro-ui'
import React, { useState } from 'react'

import api, { getContract, host } from '../../utils/api'
import request from '../../utils/request'
import { useAsyncEffect } from '../../utils/index'

import IconCert from '../../images/icon-cert.png'
import IconRealname from '../../images/icon-realname.png'
import IconSettle from '../../images/icon-settle.png'
import IconContract from '../../images/icon-contract.png'
import IconDocument from '../../images/icon-document.png'
import IconDownload from '../../images/icon-download.png'
import IconBank from '../../images/icon-bank.png'

import './mine.less'

interface IUserInfo {
  nickName: string,
  gender: number,
  avatarUrl: string,
  language: string,
  city?: string,
  province?: string,
  country?: string
}

function Mine() {
  useDidShow(() => {
    setNavigationBarTitle({
      title: '我的'
    })
    try {
      const data = Taro.getStorageSync('userInfo')
      if (!data) {
        Taro.getSetting({
          success: (res) => {
            if (res.authSetting['scope.userInfo']) {
              Taro.getUserInfo({
                success: (res) => {
                  console.log(res)
                  Taro.setStorage({
                    key: 'userInfo',
                    data: res.userInfo
                  })
                  setUserInfo(res.userInfo)
                  console.log(userInfo)
                },
                fail: (err) => {
                  console.log(err)
                }
              })
            } else {
              redirectTo({
                url: '/pages/auth/auth'
              })
            }
          }
        })

      } else {
        setUserInfo(data)
        const loginData = Taro.getStorageSync('loginInfo')
        console.log(loginData)
        setUserName(loginData.username)
        setRealName(loginData.real_name)
        request(api.userInfo, 'GET').then(data => {
          setUserName(data.member.username)
          setRealName(data.member.real_name)
          if(data.member.real_name_status === -1) {
            Taro.showToast({
              title: '请先完成认证信息',
              icon: 'none'
            })
            Taro.navigateTo({
              url: '/pages/steps/steps?type=1'
            })
          } else if(data.member.card_status === -1) {
            Taro.navigateTo({
              url: '/pages/steps/steps?type=2'
            })
          } else if(data.member.is_protocol === -1) {
            Taro.navigateTo({
              url: '/pages/steps/steps?type=4'
            })
          }
          getData()
        })
      }
    } catch (error) {
      Taro.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      })
    }
  })
  const [userInfo, setUserInfo] = useState<IUserInfo>({})
  const [userName, setUserName] = useState('')
  const [realName, setRealName] = useState('')
  const [contractInfo, setContract] = useState({})
  const [trustInfo, setTrust] = useState({})
  useAsyncEffect(async () => {

  }, [])
  const getData = async () => {
    const contract = await request(getContract, 'GET', {
    })
    let _count = contract.result.length
    if(_count > 0) {
      for(let i = 0; i< _count; i++) {
        if(contract.result[i].contract_template_id == 2) {
          setContract(contract.result[i])
        } else if(contract.result[i].contract_template_id == 3) {
          setTrust(contract.result[i])
        }
      }
    }
    try {
    } catch (err) {
      Taro.showToast({
        title: '载入远程数据失败',
        icon: 'none'
      })
    }
  }
  const downloadContract = (id) => {
    request(api.downloadContract, 'GET', {
      id
    }).then(res => {
      Taro.showLoading({
        title: '加载中'
      })
      let url = res.fileUrl
      Taro.downloadFile({
        url: url,
        success: function (res) {
          let Path = res.tempFilePath
          Taro.openDocument({
            filePath: Path,
            fileType: 'pdf',
            success: function (res) {
            }
          })
        },
        complete: function () {
          Taro.hideLoading()
        },
        fail: function (res) {
          console.log(res);
        }
      })
    })
  }

  return (
    <View className='mine'>
      <View className='layout'>
        <View className='bg'></View>
        <View className='top'></View>
        <View className='group head'>
          <Image src={userInfo.avatarUrl} className='avatar'></Image>
          <View className='name'>{realName}</View>
          <View className='account'>登录账号：{userName}</View>
        </View>
        <View className='cell-group group'>
          <Navigator url='/pages/ca/ca' className='cell-item link'>
            <Image mode='aspectFill' className='icon' src={IconCert} />
            <Text className='cell-title'>CA证书</Text>
            <AtIcon value='chevron-right' size='16' color='#333'></AtIcon>
          </Navigator>
          <Navigator url='/pages/realname/realname' className='cell-item link'>
            <Image mode='aspectFill' className='icon' src={IconRealname} />
            <Text className='cell-title'>实名信息</Text>
            <AtIcon value='chevron-right' size='16' color='#333'></AtIcon>
          </Navigator>
          <Navigator url='/pages/bank/bank' className='cell-item link'>
            <Image mode='aspectFill' className='icon' src={IconBank} />
            <Text className='cell-title'>银行信息</Text>
            <AtIcon value='chevron-right' size='16' color='#333'></AtIcon>
          </Navigator>
          <View className='cell-item'>
            <Image mode='aspectFill' className='icon' src={IconContract} />
            <Text className='cell-title'>{contractInfo.contract_title || '请完成认证后查看'}</Text>
            <View className='cell-value'>
              <Image mode='aspectFill' onClick={downloadContract.bind(this, contractInfo.id)} className='btn icon' src={IconDownload} />
            </View>
          </View>
          <View className='cell-item'>
            <Image mode='aspectFill' className='icon' src={IconContract} />
            <Text className='cell-title'>{trustInfo.contract_title || '请完成认证后查看'}</Text>
            <View className='cell-value'>
              {/* <Image mode='aspectFill' onClick={goToWebview} className='btn icon' src={IconDocument} /> */}
              <Image mode='aspectFill' onClick={downloadContract.bind(this, trustInfo.id)} className='btn icon' src={IconDownload} />
            </View>
          </View>
        </View>
      </View>
    </View>
  )
}

export default Mine
